//
//  WLMRefreshControl.swift
//  WeiBo
//
//  Created by Eric on 2017-01-10.
//  Copyright © 2017 Eric. All rights reserved.
//

import UIKit

enum RefreshState: Int {
    case Normal = 0
    case Already
    case Refreshing
}

private let refreshHeight: CGFloat = 60
class WLMRefreshControl: UIControl {

    //懒加载
    var scrollView: UIScrollView?
    private lazy var tipLabel: UILabel = UILabel(text: "正在刷新", fonSize: 14, textColor: UIColor.orange)
    private lazy var arrowIcon: UIImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    private lazy var indicator: UIActivityIndicatorView =  UIActivityIndicatorView(activityIndicatorStyle: .white)
    private lazy var backImageView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

    //MARK: - 判断刷新状态
    var currentState: RefreshState = .Normal {
        didSet {
            switch currentState {
            case .Normal:
                tipLabel.text = "下拉刷新"
                indicator.stopAnimating()
                arrowIcon.isHidden = false
                UIView.animate(withDuration: 0.25) {
                    self.arrowIcon.transform = CGAffineTransform.identity
                }
                if oldValue == .Refreshing {
                    UIView.animate(withDuration: 0.25, animations: {
                        self.scrollView!.contentInset.top = self.scrollView!.contentInset.top - refreshHeight
                    })
                }
                
            case .Already:
                tipLabel.text = "松手刷新"
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowIcon.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
                
            case .Refreshing:
                tipLabel.text = "正在刷新..."
                indicator.startAnimating()
                arrowIcon.isHidden = true
                sendActions(for: .valueChanged)
                UIView.animate(withDuration: 0.25, animations: { 
                    self.scrollView!.contentInset.top = self.scrollView!.contentInset.top + refreshHeight
                })
            }
        }
    }
    //MARK: - 结束刷新
    func endRefreshing() {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.25) {
            self.currentState = .Normal
        }
    }
    
    //MARK: - 初始化
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshHeight, width: ScreenWidth, height: refreshHeight)
        super.init(frame: rect)
        self.backgroundColor = UIColor.randomFlat
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        if let fatherView = newSuperview as? UIScrollView {
            self.scrollView = fatherView
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let offsetY = self.scrollView?.contentOffset.y ?? 0
        let targetOffsetY = -(self.scrollView!.contentInset.top + refreshHeight)
        if scrollView!.isDragging {
            if currentState == .Normal && offsetY < targetOffsetY {
                currentState = .Already
            }
            else if currentState == .Already && offsetY > targetOffsetY {
                currentState = .Normal
            }
        }
        else {
            if currentState == .Already {
                currentState = .Refreshing
            }
        }
    }
    
    //UI
    private func setupUI() {
        addSubview(backImageView)
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicator)
        
        backImageView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
        }
        
        tipLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        
        arrowIcon.snp.makeConstraints { (make) in
            make.right.equalTo(tipLabel.snp.left).offset(-5)
            make.centerY.equalTo(tipLabel)
        }
        
        indicator.snp.makeConstraints { (make) in
            make.center.equalTo(arrowIcon)
        }
    }
    
}

